<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="./js/vue.js"></script>
    <title>列表排序</title>
  </head>
  <body>
    <div id="root">
      <h2>人员列表</h2>
      <input type="text" placeholder="请输入名字" v-model="keyword" />
      <ul>
        <li v-for="obj in filPersons" :key="obj.id">
          {{obj.name}} - {{obj.age}}
        </li>
      </ul>
      <button @click="softType=2">年龄升序</button>
      <button @click="softType=1">年龄降序</button>
      <button @click="softType=0">原顺序</button>
    </div>
    <script>
      Vue.config.productionTip = false; // 关闭使用开发版本提示
      const source = [
        { id: "001", name: "马冬梅", age: 50 },
        { id: "002", name: "周冬雨", age: 40 },
        { id: "003", name: "周杰伦", age: 60 },
        { id: "004", name: "温兆伦", age: 30 },
      ];
      new Vue({
        el: "#root",
        data: {
          keyword: "",
          softType: 0, // 0原序 1降序 2升序
          persons: source,
          filPersons: [],
        },
        watch: {
          keyword: {
            immediate: true, // 直接执行，刷新即可出现全部提示，因为匹配不到空字符串
            handler(val) {
              this.filPersons = this.persons.filter((obj) => {
                return obj.name.indexOf(val) !== -1;
              });
            },
          },
          softType() {
            const arr = JSON.parse(JSON.stringify(this.persons));
            // 判断排序
            if (this.softType !== 0) {
              arr.sort((a, b) => {
                return this.softType === 1 ? b.age - a.age : a.age - b.age;
              });
            }
            this.filPersons = arr;
          },
        },
      });
    </script>
  </body>
</html>
